<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="en">

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
    <title>个人理财系统</title>
    <!-- 引入bootstrap样式 -->
    <link th:href="@{/bootstrap/css/bootstrap.css}" rel="stylesheet" type="text/css">
    <!--图标库-->
    <link th:href="@{/lyear/css/materialdesignicons.min.css}" rel="stylesheet" type="text/css" />
    <!--弹出框样式-->
    <link th:href="@{/lyear/jconfirm/jquery-confirm.min.css}" rel="stylesheet" type="text/css" />
    <!--自定义样式-->
    <link href="../lyear/css/style.min.css" th:href="@{/lyear/css/style.min.css}" rel="stylesheet" type="text/css" />

</head>

<body>
    <div class="lyear-layout-web">
        <div class="lyear-layout-container">
            <!--左侧导航-->
            <div th:replace="user/common/leftbar::#leftbaraside"></div>
            <!--头部信息-->
            <div th:replace="user/common/topbar::#topbarheader"></div>

            <!--页面主要内容-->
            <main class="lyear-layout-content">
                <div class="container-fluid">
                    <div class="row">
                        <div class="col-lg-12">
                            <div class="card">
                                <div class="card-header">
                                    <h4>我的理财</h4>
                                </div>

                                <div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true">

                                    <!--零钱理财 -->
                                    <div class="panel panel-primary">
                                        <div class="panel-heading" role="tab" id="headingOne">
                                            <h4 class="panel-title">
                                                <a role="button" data-toggle="collapse" data-parent="#accordion"
                                                    href="#collapseOne" aria-expanded="true"
                                                    aria-controls="collapseOne">
                                                    零钱理财 <span class="total-profit-change"
                                                        style="color:#FFD700; margin-left:10px; font-size:0.9em;"></span>
                                                </a>
                                            </h4>
                                        </div>
                                        <div id="collapseOne"
                                            th:class="${session.myFinanceActiveUrl=='changeMoneyActive'?'panel-collapse collapse in':'panel-collapse collapse'}"
                                            class="panel-collapse collapse in" role="tabpanel"
                                            aria-labelledby="headingOne">
                                            <div th:if="${!userChangeMoneyList.isEmpty()}" class="panel-body">

                                                <table class="table table-hover table-striped">
                                                    <thead>
                                                        <tr>
                                                            <th class="info">序号</th>
                                                            <th class="info">产品名称</th>
                                                            <th class="info">起投金额</th>
                                                            <th class="info">起投时间</th>
                                                            <th class="info">投资期限</th>
                                                            <th class="info">收益</th>
                                                            <th class="info">平均收益率</th>
                                                            <th class="info">投资状态</th>
                                                            <th class="info">相关操作</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        <tr th:each="ucm:${userChangeMoneyList}">
                                                            <td th:text="${ucmStat.index+1}"></td>
                                                            <td th:text="${ucm.changeMoney.name}"></td>
                                                            <td
                                                                th:text="${#numbers.formatDecimal(ucm.changeMoney.invesmoney,1,2)}+'元'">
                                                            </td>
                                                            <td th:text="${#dates.format(ucm.starttime, 'yyyy-MM-dd')}">
                                                            </td>
                                                            <td th:text="${ucm.changeMoney.investerm}"></td>
                                                            <td th:text="${#numbers.formatDecimal(ucm.profit,1,2)}+'元'">
                                                            </td>
                                                            <td
                                                                th:text="${#numbers.formatDecimal(ucm.averyield*100,1,2)}+'%'">
                                                            </td>
                                                            <td th:if="${ucm.status==1}" th:text="持有中"></td>
                                                            <td th:if="${ucm.status==2}" th:text="已失效"></td>
                                                            <td th:if="${ucm.status==3}" th:text="已撤销"></td>
                                                            <td>
                                                                <button class="btn btn-danger btn-sm ucm_btn"
                                                                    th:attr="ucmBtnStatus=${ucm.status},ucmBtnId=${ucm.id},ucmBtnName=${ucm.changeMoney.name}">
                                                                    <span class="glyphicon glyphicon-remove"
                                                                        aria-hidden="true"></span> 撤销
                                                                </button>
                                                            </td>
                                                        </tr>
                                                    </tbody>
                                                </table>

                                            </div>
                                            <div th:if="${userChangeMoneyList.isEmpty()}" class="panel-body">
                                                <h4>很抱歉！暂时还没有查询到您的零钱理财信息</h4>
                                            </div>
                                        </div>
                                    </div>

                                    <!--工资理财 -->
                                    <div class="panel panel-primary">
                                        <div class="panel-heading" role="tab" id="headingTwo">
                                            <h4 class="panel-title">
                                                <a class="collapsed" role="button" data-toggle="collapse"
                                                    data-parent="#accordion" href="#collapseTwo" aria-expanded="false"
                                                    aria-controls="collapseTwo">
                                                    工资理财 <span class="total-profit-pay"
                                                        style="color:#FFD700; margin-left:10px; font-size:0.9em;"></span>
                                                </a>
                                            </h4>
                                        </div>
                                        <div id="collapseTwo"
                                            th:class="${session.myFinanceActiveUrl=='payMoneyActive'?'panel-collapse collapse in':'panel-collapse collapse'}"
                                            role="tabpanel" aria-labelledby="headingTwo">
                                            <div th:if="${!userPayMoneyList.isEmpty()}" class="panel-body">
                                                <table class="table table-hover table-striped">
                                                    <thead>
                                                        <tr>
                                                            <th class="info">序号</th>
                                                            <th class="info">产品名称</th>
                                                            <th class="info">起投金额</th>
                                                            <th class="info">起投时间</th>
                                                            <th class="info">投资期限</th>
                                                            <th class="info">收益</th>
                                                            <th class="info">平均收益率</th>
                                                            <th class="info">投资状态</th>
                                                            <th class="info">相关操作</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        <tr th:each="upm:${userPayMoneyList}">
                                                            <td th:text="${upmStat.index+1}"></td>
                                                            <td th:if="${upm.payMoney.type==1}" th:text="国债"></td>
                                                            <td th:if="${upm.payMoney.type==2}" th:text="期货"></td>
                                                            <td
                                                                th:text="${#numbers.formatDecimal(upm.payMoney.monthmoney,1,2)}+'元'">
                                                            </td>
                                                            <td th:text="${#dates.format(upm.starttime, 'yyyy-MM-dd')}">
                                                            </td>
                                                            <td th:text="${upm.payMoney.investerm}"></td>
                                                            <td th:text="${#numbers.formatDecimal(upm.profit,1,2)}+'元'">
                                                            </td>
                                                            <td
                                                                th:text="${#numbers.formatDecimal(upm.averyield*100,1,2)}+'%'">
                                                            </td>
                                                            <td th:if="${upm.status==1}" th:text="持有中"></td>
                                                            <td th:if="${upm.status==2}" th:text="已失效"></td>
                                                            <td th:if="${upm.status==3}" th:text="已撤销"></td>
                                                            <td>
                                                                <button class="btn btn-danger btn-sm upm_btn"
                                                                    th:attr="upmBtnStatus=${upm.status},upmBtnId=${upm.id},upmBtnName=${upm.payMoney.type}">
                                                                    <span class="glyphicon glyphicon-remove"
                                                                        aria-hidden="true"></span> 撤销
                                                                </button>
                                                            </td>
                                                        </tr>
                                                    </tbody>
                                                </table>
                                            </div>
                                            <div th:if="${userPayMoneyList.isEmpty()}" class="panel-body">
                                                <h4>很抱歉！暂时还没有查询到您的工资理财信息</h4>
                                            </div>

                                        </div>
                                    </div>

                                    <!--期限理财 -->
                                    <div class="panel panel-primary">
                                        <div class="panel-heading" role="tab" id="headingThree">
                                            <h4 class="panel-title">
                                                <a class="collapsed" role="button" data-toggle="collapse"
                                                    data-parent="#accordion" href="#collapseThree" aria-expanded="false"
                                                    aria-controls="collapseTwo">
                                                    期限理财 <span class="total-profit-term"
                                                        style="color:#FFD700; margin-left:10px; font-size:0.9em;"></span>
                                                </a>
                                            </h4>
                                        </div>
                                        <div id="collapseThree"
                                            th:class="${session.myFinanceActiveUrl=='termFinancialActive'?'panel-collapse collapse in':'panel-collapse collapse'}"
                                            role="tabpanel" aria-labelledby="headingThree">
                                            <div th:if="${!userTermFinancialList.isEmpty()}" class="panel-body">

                                                <table class="table table-hover table-striped">
                                                    <thead>
                                                        <tr>
                                                            <th class="info">序号</th>
                                                            <th class="info">产品名称</th>
                                                            <th class="info">起投金额</th>
                                                            <th class="info">起投时间</th>
                                                            <th class="info">投资期限</th>
                                                            <th class="info">收益</th>
                                                            <th class="info">平均收益率</th>
                                                            <th class="info">投资状态</th>
                                                            <th class="info">相关操作</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        <tr th:each="utf:${userTermFinancialList}">
                                                            <td th:text="${utfStat.index+1}"></td>
                                                            <td th:text="${utf.termFinancial.name}"></td>
                                                            <td
                                                                th:text="${#numbers.formatDecimal(utf.termFinancial.leastmoney,1,2)}+'元'">
                                                            </td>
                                                            <td th:text="${#dates.format(utf.starttime, 'yyyy-MM-dd')}">
                                                            </td>
                                                            <td th:text="${utf.termFinancial.investerm}"></td>
                                                            <td th:text="${#numbers.formatDecimal(utf.profit,1,2)}+'元'">
                                                            </td>
                                                            <td
                                                                th:text="${#numbers.formatDecimal(utf.averyield*100,1,2)}+'%'">
                                                            </td>
                                                            <td th:if="${utf.status==1}" th:text="持有中"></td>
                                                            <td th:if="${utf.status==2}" th:text="已失效"></td>
                                                            <td th:if="${utf.status==3}" th:text="已撤销"></td>
                                                            <td>
                                                                <button class="btn btn-danger btn-sm utf_btn"
                                                                    th:attr="utfBtnStatus=${utf.status},utfBtnId=${utf.id},utfBtnName=${utf.termFinancial.name}">
                                                                    <span class="glyphicon glyphicon-remove"
                                                                        aria-hidden="true"></span> 撤销
                                                                </button>
                                                            </td>
                                                        </tr>
                                                    </tbody>
                                                </table>

                                            </div>
                                            <div th:if="${userTermFinancialList.isEmpty()}" class="panel-body">
                                                <h4>很抱歉！暂时还没有查询到您的期限理财信息</h4>
                                            </div>
                                        </div>
                                    </div>

                                    <!--基金理财 -->
                                    <div class="panel panel-primary">
                                        <div class="panel-heading" role="tab" id="headingFour">
                                            <h4 class="panel-title">
                                                <a class="collapsed" role="button" data-toggle="collapse"
                                                    data-parent="#accordion" href="#collapseFour" aria-expanded="false"
                                                    aria-controls="collapseTwo">
                                                    基金理财 <span class="total-profit-fund"
                                                        style="color:#FFD700; margin-left:10px; font-size:0.9em;"></span>
                                                </a>
                                            </h4>
                                        </div>
                                        <div id="collapseFour"
                                            th:class="${session.myFinanceActiveUrl=='fundProductActive'?'panel-collapse collapse in':'panel-collapse collapse'}"
                                            role="tabpanel" aria-labelledby="headingFour">
                                            <div th:if="${!userFundProductList.isEmpty()}" class="panel-body">

                                                <table class="table table-hover table-striped">
                                                    <thead>
                                                        <tr>
                                                            <th class="info">序号</th>
                                                            <th class="info">产品名称</th>
                                                            <th class="info">起投金额</th>
                                                            <th class="info">起投时间</th>
                                                            <th class="info">投资期限</th>
                                                            <th class="info">收益</th>
                                                            <th class="info">平均收益率</th>
                                                            <th class="info">投资状态</th>
                                                            <th class="info">相关操作</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        <tr th:each="ufp:${userFundProductList}">
                                                            <td th:text="${ufpStat.index+1}"></td>
                                                            <td th:text="${ufp.fundProduct.funddesc}"></td>
                                                            <td
                                                                th:text="${#numbers.formatDecimal(ufp.fundProduct.leastmoney,1,2)}+'元'">
                                                            </td>
                                                            <td th:text="${#dates.format(ufp.starttime, 'yyyy-MM-dd')}">
                                                            </td>
                                                            <td th:text="${ufp.fundProduct.investerm}"></td>
                                                            <td th:text="${#numbers.formatDecimal(ufp.profit,1,2)}+'元'">
                                                            </td>
                                                            <td
                                                                th:text="${#numbers.formatDecimal(ufp.averyield*100,1,2)}+'%'">
                                                            </td>
                                                            <td th:if="${ufp.status==1}" th:text="持有中"></td>
                                                            <td th:if="${ufp.status==2}" th:text="已失效"></td>
                                                            <td th:if="${ufp.status==3}" th:text="已撤销"></td>
                                                            <td>
                                                                <button class="btn btn-danger btn-sm ufp_btn"
                                                                    th:attr="ufpBtnStatus=${ufp.status},ufpBtnId=${ufp.id},ufpBtnName=${ufp.fundProduct.funddesc}">
                                                                    <span class="glyphicon glyphicon-remove"
                                                                        aria-hidden="true"></span> 撤销
                                                                </button>
                                                            </td>
                                                        </tr>
                                                    </tbody>
                                                </table>

                                            </div>
                                            <div th:if="${userFundProductList.isEmpty()}" class="panel-body">
                                                <h4>很抱歉！暂时还没有查询到您的基金理财信息</h4>
                                            </div>
                                        </div>
                                    </div>

                                </div>

                            </div>
                        </div>
                    </div>
                </div>
            </main>
            <!--End 页面主要内容-->
        </div>
    </div>

    <!-- 引入jQuery和bootstrap的js -->
    <script th:src="@{/js/jquery.js}"></script>
    <script th:src="@{/bootstrap/js/bootstrap.js}"></script>
    <!--滚动条插件-->
    <script th:src="@{/lyear/js/perfect-scrollbar.min.js}"></script>
    <!--弹出框js-->
    <script th:src="@{/lyear/jconfirm/jquery-confirm.min.js}"></script>
    <!--自定义js脚本-->
    <script th:src="@{/lyear/js/main.min.js}"></script>
    <script type="text/javascript">

        $(document).on("click", ".ucm_btn", function () {
            var userChangeMoneyId = $(this).attr("ucmBtnId");

            var status = $(this).attr("ucmBtnStatus");
            if (status == 2) {
                $.alert('已失效！无须撤销');
            } else if (status == 3) {
                $.alert('已撤销!');
            } else if (status == 1) {
                //var userId = [[${session.loginUser.id}]] ;
                //alert(userId);
                var name = $(this).attr("ucmBtnName");
                $.alert({
                    title: '提示：',
                    content: "确定撤销 <strong>" + name + "</strong> 吗？",
                    buttons: {
                        confirm: {
                            text: '确认',
                            btnClass: 'btn-primary',
                            action: function () {
                                $.ajax({
                                    url: "/user/revokeUserChangeMoney",
                                    type: "put",
                                    data: {
                                        "userChangeMoneyId": userChangeMoneyId
                                    },
                                    success: function (result) {
                                        if (result.code === 100) {
                                            $.alert('撤销成功!');
                                            setTimeout(function () {
                                                location.href = "/user/personal/toMyFinance.html";
                                            }, 1000);
                                        } else {
                                            $.alert('撤销失败!');
                                        }
                                    }
                                });
                            }
                        },
                        cancel: {
                            text: '取消',
                            action: function () {
                                $.alert('已取消!');
                            }
                        }
                    }
                });
            }
        });

        $(document).on("click", ".upm_btn", function () {
            var userPayMoneyId = $(this).attr("upmBtnId");

            var status = $(this).attr("upmBtnStatus");
            if (status == 2) {
                $.alert('已失效！无须撤销');
            } else if (status == 3) {
                $.alert('已撤销!');
            } else if (status == 1) {
                var type = $(this).attr("upmBtnName");
                var name;
                if (type == 1) {
                    name = "国债"
                } else {
                    name = "期货";
                }
                $.alert({
                    title: '提示：',
                    content: "确定撤销该 <strong>" + name + "</strong> 吗？",
                    buttons: {
                        confirm: {
                            text: '确认',
                            btnClass: 'btn-primary',
                            action: function () {
                                $.ajax({
                                    url: "/user/revokeUserPayMoney",
                                    type: "put",
                                    data: {
                                        "userPayMoneyId": userPayMoneyId
                                    },
                                    success: function (result) {
                                        if (result.code === 100) {
                                            $.alert('撤销成功!');
                                            setTimeout(function () {
                                                location.href = "/user/personal/toMyFinance.html";
                                            }, 1000);
                                        } else {
                                            $.alert('撤销失败!');
                                        }
                                    }
                                });
                            }
                        },
                        cancel: {
                            text: '取消',
                            action: function () {
                                $.alert('已取消!');
                            }
                        }
                    }
                });
            }
        });

        $(document).on("click", ".utf_btn", function () {
            var status = $(this).attr("utfBtnStatus");
            if (status == 2) {
                $.alert('已失效！无须撤销');
            } else if (status == 3) {
                $.alert('已撤销!');
            } else if (status == 1) {
                var userTermFinancialId = $(this).attr("utfBtnId");
                var name = $(this).attr("utfBtnName");
                $.alert({
                    title: '提示：',
                    content: "确定撤销 <strong>" + name + "</strong> 吗？",
                    buttons: {
                        confirm: {
                            text: '确认',
                            btnClass: 'btn-primary',
                            action: function () {
                                $.ajax({
                                    url: "/user/revokeUserTermFinancial",
                                    type: "put",
                                    data: {
                                        "userTermFinancialId": userTermFinancialId
                                    },
                                    success: function (result) {
                                        if (result.code === 100) {
                                            $.alert('撤销成功!');
                                            setTimeout(function () {
                                                location.href = "/user/personal/toMyFinance.html";
                                            }, 1000);
                                        } else {
                                            $.alert('撤销失败!');
                                        }
                                    }
                                });
                            }
                        },
                        cancel: {
                            text: '取消',
                            action: function () {
                                $.alert('已取消!');
                            }
                        }
                    }
                });
            }
        });

        $(document).on("click", ".ufp_btn", function () {
            var status = $(this).attr("ufpBtnStatus");
            if (status == 2) {
                $.alert('已失效！无须撤销');
            } else if (status == 3) {
                $.alert('已撤销!');
            } else if (status == 1) {
                var userFundProductId = $(this).attr("ufpBtnId");
                var name = $(this).attr("ufpBtnName");
                $.alert({
                    title: '提示：',
                    content: "确定撤销 <strong>" + name + "</strong> 吗？",
                    buttons: {
                        confirm: {
                            text: '确认',
                            btnClass: 'btn-primary',
                            action: function () {
                                $.ajax({
                                    url: "/user/revokeUserFundProduct",
                                    type: "put",
                                    data: {
                                        "userFundProductId": userFundProductId
                                    },
                                    success: function (result) {
                                        if (result.code === 100) {
                                            $.alert('撤销成功!');
                                            setTimeout(function () {
                                                location.href = "/user/personal/toMyFinance.html";
                                            }, 1000);
                                        } else {
                                            $.alert('撤销失败!');
                                        }
                                    }
                                });
                            }
                        },
                        cancel: {
                            text: '取消',
                            action: function () {
                                $.alert('已取消!');
                            }
                        }
                    }
                });
            }
        });

        // 添加总收益计算功能
        $(document).ready(function () {
            // 解析投资期限字符串，返回天数
            function parseInvestTerm(investTerm) {
                // 移除所有空格
                investTerm = investTerm.trim();

                if (investTerm.includes('天')) {
                    return parseInt(investTerm);
                } else if (investTerm.includes('个月')) {
                    return parseInt(investTerm) * 30;
                } else if (investTerm.includes('月')) {
                    return parseInt(investTerm) * 30;
                } else if (investTerm.includes('年')) {
                    return parseInt(investTerm.replace('一', '1').replace('二', '2').replace('三', '3')
                        .replace('四', '4').replace('五', '5').replace('半', '0.5')) * 365;
                }

                // 尝试直接解析数字
                const num = parseInt(investTerm);
                if (!isNaN(num)) {
                    return num;
                }

                // 默认返回30天
                return 30;
            }

            // 计算实际收益
            function calculateActualProfit() {
                const now = new Date();
                const currentTime = now.getTime();

                // 显示当前计算时间（调试用）
                console.log("更新收益计算，当前时间：" + now.toLocaleString());

                // 处理所有表格中的收益
                $('table tbody tr').each(function () {
                    try {
                        // 获取起投时间
                        const startTimeText = $(this).find('td:nth-child(4)').text().trim();
                        if (!startTimeText) return; // 如果没有起投时间，跳过

                        // 解析日期，格式为 yyyy-MM-dd
                        const dateParts = startTimeText.split('-');
                        if (dateParts.length !== 3) return;

                        const year = parseInt(dateParts[0]);
                        const month = parseInt(dateParts[1]) - 1; // 月份从0开始
                        const day = parseInt(dateParts[2]);

                        const startDate = new Date(year, month, day);
                        const startTime = startDate.getTime();

                        // 获取投资状态
                        const statusText = $(this).find('td:nth-child(8)').text().trim();

                        // 获取投资期限
                        const investTermText = $(this).find('td:nth-child(5)').text().trim();
                        if (!investTermText) return; // 如果没有投资期限，跳过

                        // 将文字形式的投资期限转换为天数
                        let investTermDays;
                        if (investTermText === '半年') {
                            investTermDays = 183; // 半年约等于183天
                        } else if (investTermText === '一个月') {
                            investTermDays = 30;
                        } else if (investTermText === '一年') {
                            investTermDays = 365;
                        } else {
                            // 如果不匹配任何已知的文字形式，返回30天作为默认值
                            investTermDays = 30;
                        }

                        // 获取预期收益
                        const profitCell = $(this).find('td:nth-child(6)');

                        // 如果单元格中已经有实际收益信息，先移除它
                        let originalProfitText = profitCell.text().trim();
                        // 移除所有"(实际: x.xx元)"文本
                        originalProfitText = originalProfitText.replace(/\(实际:.*?\)/g, '').trim();

                        // 提取数字部分
                        const profitMatch = originalProfitText.match(/(\d+\.\d+)/);
                        if (!profitMatch) return;

                        const profit = parseFloat(profitMatch[1]);

                        // 计算实际收益
                        let actualProfit;

                        // 如果是已失效或已撤销的投资，直接显示预期收益
                        if (statusText === '已失效' || statusText === '已撤销') {
                            actualProfit = profit;
                        }
                        // 如果是2023年之前的投资，直接显示预期收益
                        else if (year < 2023) {
                            actualProfit = profit;
                        }
                        // 如果起投时间在未来，实际收益为0
                        else if (startTime > currentTime) {
                            actualProfit = 0;
                        }
                        else {
                            // 计算投资结束时间
                            const endTime = new Date(startTime + (investTermDays * 24 * 60 * 60 * 1000));

                            // 如果当前时间已经超过了投资结束时间，则实际收益等于预期收益
                            if (currentTime >= endTime.getTime()) {
                                actualProfit = profit;
                            } else {
                                // 计算已投资的毫秒数
                                const investedMillis = currentTime - startTime;

                                // 计算已投资的天数
                                const investedDays = investedMillis / (1000 * 60 * 60 * 24);

                                // 计算投资时间比例(不超过1)
                                const timeRatio = Math.min(1.0, investedDays / investTermDays);

                                // 计算实际收益
                                actualProfit = (profit * timeRatio).toFixed(2);
                            }
                        }

                        // 获取当前显示的实际收益值（如果有）
                        const actualProfitSpan = profitCell.find('span.actual-profit');
                        const oldValue = actualProfitSpan.length > 0 ?
                            parseFloat(actualProfitSpan.attr('data-value') || '0') : 0;

                        // 如果值有变化，添加高亮效果
                        let highlightClass = '';
                        if (oldValue < actualProfit) {
                            highlightClass = 'text-success';
                        }

                        // 如果单元格中已经有实际收益信息，更新它
                        if (actualProfitSpan.length > 0) {
                            actualProfitSpan.attr('data-value', actualProfit);
                            actualProfitSpan.attr('class', 'actual-profit ' + highlightClass);
                            actualProfitSpan.text('(实际: ' + actualProfit + '元)');
                        } else {
                            // 否则，添加新的实际收益信息
                            profitCell.html(originalProfitText + '<br><span class="actual-profit ' + highlightClass + '" data-value="' + actualProfit + '" style="color:#4CAF50;">(实际: ' + actualProfit + '元)</span>');
                        }
                    } catch (e) {
                        console.error("计算错误:", e);
                    }
                });
            }

            // 页面加载完成后计算实际收益
            calculateActualProfit();

            // 设置定时器，每秒更新一次实际收益（演示用，实际可以设置更长的间隔）
            setInterval(calculateActualProfit, 1000);

            // 添加CSS样式，用于动画效果
            $("<style>")
                .prop("type", "text/css")
                .html(`
                    .text-success {
                        animation: highlight 1s ease-in-out;
                    }
                    @keyframes highlight {
                        0% { color: #4CAF50; }
                        50% { color: #FFC107; }
                        100% { color: #4CAF50; }
                    }
                `)
                .appendTo("head");
        });

        // 添加计算总收益并显示在标题上的函数
        function calculateTotalProfits() {
            // 计算零钱理财总收益
            let totalChangeProfit = 0;
            $('#collapseOne tbody tr').each(function () {
                const profitCell = $(this).find('td:nth-child(6)');
                const profitText = profitCell.text().trim();
                const actualProfitSpan = profitCell.find('span.actual-profit');

                if (actualProfitSpan.length > 0) {
                    const actualProfit = parseFloat(actualProfitSpan.attr('data-value') || '0');
                    totalChangeProfit += actualProfit;
                } else {
                    const profitMatch = profitText.match(/(\d+\.\d+)/);
                    if (profitMatch) {
                        totalChangeProfit += parseFloat(profitMatch[1]);
                    }
                }
            });

            // 计算工资理财总收益
            let totalPayProfit = 0;
            $('#collapseTwo tbody tr').each(function () {
                const profitCell = $(this).find('td:nth-child(6)');
                const profitText = profitCell.text().trim();
                const actualProfitSpan = profitCell.find('span.actual-profit');

                if (actualProfitSpan.length > 0) {
                    const actualProfit = parseFloat(actualProfitSpan.attr('data-value') || '0');
                    totalPayProfit += actualProfit;
                } else {
                    const profitMatch = profitText.match(/(\d+\.\d+)/);
                    if (profitMatch) {
                        totalPayProfit += parseFloat(profitMatch[1]);
                    }
                }
            });

            // 计算期限理财总收益
            let totalTermProfit = 0;
            $('#collapseThree tbody tr').each(function () {
                const profitCell = $(this).find('td:nth-child(6)');
                const profitText = profitCell.text().trim();
                const actualProfitSpan = profitCell.find('span.actual-profit');

                if (actualProfitSpan.length > 0) {
                    const actualProfit = parseFloat(actualProfitSpan.attr('data-value') || '0');
                    totalTermProfit += actualProfit;
                } else {
                    const profitMatch = profitText.match(/(\d+\.\d+)/);
                    if (profitMatch) {
                        totalTermProfit += parseFloat(profitMatch[1]);
                    }
                }
            });

            // 计算基金理财总收益
            let totalFundProfit = 0;
            $('#collapseFour tbody tr').each(function () {
                const profitCell = $(this).find('td:nth-child(6)');
                const profitText = profitCell.text().trim();
                const actualProfitSpan = profitCell.find('span.actual-profit');

                if (actualProfitSpan.length > 0) {
                    const actualProfit = parseFloat(actualProfitSpan.attr('data-value') || '0');
                    totalFundProfit += actualProfit;
                } else {
                    const profitMatch = profitText.match(/(\d+\.\d+)/);
                    if (profitMatch) {
                        totalFundProfit += parseFloat(profitMatch[1]);
                    }
                }
            });

            // 计算总收益
            const totalProfit = totalChangeProfit + totalPayProfit + totalTermProfit + totalFundProfit;

            // 显示各类理财总收益
            $('.total-profit-change').text('(总收益: ' + totalChangeProfit.toFixed(2) + '元)');
            $('.total-profit-pay').text('(总收益: ' + totalPayProfit.toFixed(2) + '元)');
            $('.total-profit-term').text('(总收益: ' + totalTermProfit.toFixed(2) + '元)');
            $('.total-profit-fund').text('(总收益: ' + totalFundProfit.toFixed(2) + '元)');

            // 更新整体总收益（可选，如果需要在页面顶部显示）
            // $('.total-all-profits').text('总收益: ' + totalProfit.toFixed(2) + '元');
        }

        $(document).ready(function () {
            // 页面加载后计算初始总收益
            calculateTotalProfits();

            // 在每次更新实际收益后重新计算总收益
            // 修改calculateActualProfit函数末尾，添加总收益计算
            const originalCalculateActualProfit = calculateActualProfit;
            calculateActualProfit = function () {
                originalCalculateActualProfit.apply(this, arguments);
                calculateTotalProfits();
            };
        });

    </script>
</body>

</html>